<?php

namespace app\admin\controller;

use app\common\controller\Backend;
use app\common\logic\VodLogic;
use fast\Tree;
use think\Db;
use think\Exception;

/**
 * 资源
 *
 * @icon fa fa-circle-o
 */
class VVideo extends Backend
{

    /**
     * VVideo模型对象
     * @var \app\admin\model\VVideo
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\VVideo;
        $this->view->assign("mediaTypeList", $this->model->getMediaTypeList());
        $this->view->assign("isSaveList", $this->model->getIsSaveList());
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    function create_video()
    {
        $title = input('title');
        $desc = input('desc');
        $filename = input('filename');

        if (empty($title)) return ['code' => 0, 'msg' => '名称不能为空'];
        if (empty($desc)) return ['code' => 0, 'msg' => '描述不能为空'];
        if (empty($filename)) return ['code' => 0, 'msg' => '文件名不能为空'];

        $mad_content = input('mad_content');
        $media_type = input('media_type', 1);

        try {
            $result = VodLogic::create_upload_video([
                'title' => $title,
                'srcFile' => $filename,
                'desc' => $desc,
            ]);
        } catch (Exception $e) {
            log_print($e->getMessage());
            return ['code' => 0, 'msg' => '上传出错'];
        }

        if (isset($result->UploadAddress)) {
//            log_print($result);
            $video_db = Db::name('v_video');
            $video_db->insert([
                'video_id' => $result->VideoId,
                'title' => $title,
                'description' => $desc,
                'media_type' => $media_type,
                'mad_content' => $mad_content,
                'cover_image' => "https://html.bigchun.com/ke.bigchun.com/static/home/image/voice_back.png",
                'createtime' => time(),
            ]);

            return ['code' => 1, 'msg' => 'success', 'data' => [
                'uploadAuth' => $result->UploadAuth,
                'uploadAddress' => $result->UploadAddress,
                'videoId' => $result->VideoId,
            ]];
        }
        return ['code' => 0, 'msg' => '获取上传凭证失败'];
    }

    function save_video()
    {
        $video_id = input('video_id');
        if (empty($video_id)) return ['code' => 0, 'msg' => '视频凭证不能为空'];

        $video_db = Db::name('v_video');
        $video_db->where('video_id', $video_id)->update(['is_save' => 1]);
        return ['code' => 1, 'msg' => '上传成功'];
    }

    function update_video()
    {
        $video_id = input('video_id');
        if (empty($video_id)) return ['code' => 0, 'msg' => '视频凭证不能为空'];

        $title = input('title');
        $desc = input('description');
        $img = input('cover_url');

        if (empty($title)) return ['code' => 0, 'msg' => '名称不能为空'];
        if (empty($desc)) return ['code' => 0, 'msg' => '描述不能为空'];
        $media_type = input('media_type', 1);

        $exist_id = Db::name('video')->where('id', $video_id)->find();
        if ($exist_id < 1) return ['code' => 1, 'msg' => '未找到视频id'];

        Db::name('video')->where('id', $video_id)->update([
            'title' => $title,
            'description' => $desc,
            'media_type' => $media_type,
            'cover_url' => $img,
        ]);

        return ['code' => 1, 'msg' => '上传成功'];
    }

    function get_data()
    {
//        $list = $this->model->order("id asc")->field('id,title')->select();
//        $list = collection($list)->toArray();
//        $result = array("total" => count($list), "rows" => $list);
//
//        return json($result);


        //设置过滤方法
        $this->request->filter(['strip_tags', 'htmlspecialchars']);

        //搜索关键词,客户端输入以空格分开,这里接收为数组
        $word = (array)$this->request->request("q_word/a");
        //当前页
        $page = $this->request->request("pageNumber");
        //分页大小
        $pagesize = $this->request->request("pageSize");
        //搜索条件
        $andor = $this->request->request("andOr", "and", "strtoupper");
        //排序方式
        $orderby = (array)$this->request->request("orderBy/a");
        //显示的字段
        $field = $this->request->request("showField");
        //主键
        $primarykey = $this->request->request("keyField");
        //主键值
        $primaryvalue = $this->request->request("keyValue");
        //搜索字段
        $searchfield = (array)$this->request->request("searchField/a");
        //自定义搜索条件
        $custom = (array)$this->request->request("custom/a");
        //是否返回树形结构
        $istree = $this->request->request("isTree", 0);
        $ishtml = $this->request->request("isHtml", 0);
        if ($istree) {
            $word = [];
            $pagesize = 99999;
        }
        $order = [];
        foreach ($orderby as $k => $v) {
            $order[$v[0]] = $v[1];
        }
        $field = $field ? $field : 'name';

        //如果有primaryvalue,说明当前是初始化传值
        if ($primaryvalue !== null) {
            $where = [$primarykey => ['in', $primaryvalue]];
        } else {
            $where = function ($query) use ($word, $andor, $field, $searchfield, $custom) {
                $logic = $andor == 'AND' ? '&' : '|';
                $searchfield = is_array($searchfield) ? implode($logic, $searchfield) : $searchfield;
                foreach ($word as $k => $v) {
                    $query->where(str_replace(',', $logic, $searchfield), "like", "%{$v}%");
                }
                if ($custom && is_array($custom)) {
                    foreach ($custom as $k => $v) {
                        if (is_array($v) && 2 == count($v)) {
                            $query->where($k, trim($v[0]), $v[1]);
                        } else {
                            $query->where($k, '=', $v);
                        }
                    }
                }
            };
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            $this->model->where($this->dataLimitField, 'in', $adminIds);
        }
        $list = [];
        $total = $this->model->where($where)->count();
        if ($total > 0) {
            if (is_array($adminIds)) {
                $this->model->where($this->dataLimitField, 'in', $adminIds);
            }
            $datalist = $this->model->where($where)
                ->order("id asc")
                ->page($page, $pagesize)
                ->field('id,title')
                ->select();
            foreach ($datalist as $index => $item) {
                unset($item['password'], $item['salt']);
                $list[] = [
                    $primarykey => isset($item[$primarykey]) ? $item[$primarykey] : '',
                    $field      => isset($item[$field]) ? $item[$field] : '',
                    'pid'       => isset($item['pid']) ? $item['pid'] : 0
                ];
            }
            if ($istree) {
                $tree = Tree::instance();
                $tree->init(collection($list)->toArray(), 'pid');
                $list = $tree->getTreeList($tree->getTreeArray(0), $field);
                if (!$ishtml) {
                    foreach ($list as &$item) {
                        $item = str_replace('&nbsp;', ' ', $item);
                    }
                    unset($item);
                }
            }
        }
        //这里一定要返回有list这个字段,total是可选的,如果total<=list的数量,则会隐藏分页按钮
        return json(['list' => $list, 'total' => $total]);
    }
}
